﻿using System;

namespace Hanhud.Pattern
{
    public static class CPageSingleton<T> where T : class , new()
    {
        // static constructor, 
        // runtime ensures thread safety

        /// <summary>
        /// The _instance.
        /// </summary>
        private static T _instance;

        /// <summary>
        /// Gets Instance.
        /// </summary>
        public static T Instance
        {
            get
            {
                return GetInstance();
            }

            private set
            {
                _instance = value;
            }
        }

        /// <summary>
        /// The get instance.
        /// </summary>
        /// <returns>
        /// </returns>
        private static T GetInstance()
        {
            if (_instance == null)
            {
                _instance = (T)Activator.CreateInstance(typeof(T), true);
            }

            string typeStr = typeof(T).ToString();
            if (!CBaseContext.Current.Items.ContainsKey(typeStr))
                CBaseContext.Current.Items.Add(typeStr, null);

            return (T)(CBaseContext.Current.Items[typeStr] ?? (CBaseContext.Current.Items[typeStr] = Activator.CreateInstance(typeof(T), true)));
        }
    }
}
